home *** CD-ROM | disk | FTP | other *** search
- Path: news.lpr.carel.fi!usenet
- From: Ari Lukumies <aril@cmt.lpr.mail.carel.fi>
- Newsgroups: comp.lang.c++
- Subject: Re: External access to private class variables
- Date: Fri, 02 Feb 1996 14:57:18 +0200
- Organization: Carelcomp Forest
- Message-ID: <31120A2E.59D1@cmt.lpr.mail.carel.fi>
- References: <4ermr9$ii7@cloner2.ix.netcom.com>
- NNTP-Posting-Host: renoir.cclahti.carel.fi
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b6a (WinNT; I)
-
- Eugene S. Thompson wrote:
- >
- > I was playing around with references and ran across this situation. I'm
- > sure it's not original, so I was hoping someone could tell me if it is
- > an intentional implementation of C++ or if it is a bug.
- >
- > class X
- > {
- > private:
- > int value;
- > public:
- > X (int n = 0) { value = n; }
- > int& GSValue () { return value; } // return a reference to the
- > // private member "value"
- > };
- > .
- > .
- > .
- > main ()
- > {
- > X x1 (20);
- >
- > printf ("%d\n", x1.GSValue ()); // 20
- >
- > int* pntr = &(x1.GSValue ());
- >
- > printf ("%d\n", *pntr); // 20
- >
- > *pntr = 30;
- > printf ("%d\n", x1.GSValue ()); // 30 -> We now have external
- > // access to a private member.
- > }
- >
- > I realize that this implementation is contrived, but I'm sure there are
- > additional ways of gaining such access. So, what's the deal?
- >
- > Gene
-
- This is normal behaviour. Only, using such constructs is a bad programming
- practice, since the meaning of declaring a variable as private is to disallow
- direct access to it. What if you compiled this class and produced a library that
- other people can use. Later, you found out that you'll have to change 'int value;'
- to 'char value[10];'. Now, if you had declared access functions (GetValue,
- SetValue) that internally get/set the value, you could just modify the passed
- value to suit the new format. But if you allowed your library users gain direct
- access to it, they'd also have to change all their code directly using that
- variable. Instead of
-
- int& GSValue () { return value; }
-
- you should use
-
- const int& GSValue() { return value; }
-
- That can still be called, but now the callers cannot modify what you gave them.
-
- Later,
- AriL
-
- --
- All my opinions are mine and mine alone.
-